﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using Habanero.Base.Exceptions;

namespace Firestarter.DB.Schema.Test.Logic
{
    /// <summary>
    /// Will read a SQL Server generated T-SQL script from a file breaking the script into a series of executable statements
    /// The statements are split on each occurrance of the T-SQL GO keyword which will cause an exception if left as part of any sql script run via an ADO command
    /// </summary>
    public class SqlScriptReader
    {
        public string SqlScriptFileName { get; private set; }
        public IList<string> SqlStatements { get; private set; } 
        public SqlScriptReader()
        {
            SqlStatements = new List<string>();
        }

        public virtual void LoadScript(string sqlSctiptFileName)
        {
            SqlScriptFileName = sqlSctiptFileName;
            if (string.IsNullOrEmpty(SqlScriptFileName)) throw new HabaneroDeveloperException("No SQL Script file name was supplied in the consrtuctor");
            using (var fs = new FileStream(SqlScriptFileName,FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite))
            {
                LoadScript(fs);
            }
        }

        public virtual void LoadScript(Stream stream)
        {
            using (var sr = new StreamReader(stream))
            {
                var sb = new StringBuilder("");

                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Contains("GO"))
                    {
                        TryAddSqlStatment(sb);

                        sb = new StringBuilder("");
                    }
                    else
                    {
                        sb.AppendLine(line);
                    }
                }
                TryAddSqlStatment(sb);
            }
        }


        private void TryAddSqlStatment(StringBuilder sb)
        {
            if (sb.ToString().Length > 0) SqlStatements.Add(sb.ToString());
        }
    }
}